package cn.mulanbay.auth.handler;

import cn.mulanbay.api.system.service.RemoteMessageService;
import cn.mulanbay.api.system.service.RemoteUserService;
import cn.mulanbay.business.bean.SysMessageBean;
import cn.mulanbay.business.bean.UserLoginInfo;
import cn.mulanbay.business.handler.BaseHandler;
import cn.mulanbay.business.handler.ThreadPoolHandler;
import cn.mulanbay.common.exception.ErrorCode;
import cn.mulanbay.common.util.BeanFactoryUtil;
import cn.mulanbay.persistent.enums.MessageSource;
import cn.mulanbay.persistent.enums.UserType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *
 * @author fenghong
 * @create 2022-01-16 10:00
 */
@Component
public class LogHandler extends BaseHandler {

    private static final Logger logger = LoggerFactory.getLogger(LogHandler.class);

    @Autowired
    ThreadPoolHandler threadPoolHandler;

    public LogHandler() {
        super("日志处理");
    }

    /**
     * 更新用户登录信息
     * @param uli
     */
    public void addUserLogin(UserLoginInfo uli){
        try {
            threadPoolHandler.pushThread(() -> {
                RemoteUserService remoteUserService = BeanFactoryUtil.getBean(RemoteUserService.class);
                remoteUserService.updateLoginInfo(uli);
                logger.debug("增加登录日志,userId:"+uli.getUserId());

                if(UserType.ADMIN==uli.getLoginType()){
                    RemoteMessageService remoteMessageService = BeanFactoryUtil.getBean(RemoteMessageService.class);
                    SysMessageBean smb = new SysMessageBean();
                    smb.setCode(ErrorCode.ADMIN_LOGIN);
                    smb.setTitle("UserId="+uli.getUserId()+"在管理员端登录");
                    smb.setContent("管理员登录");
                    smb.setSource(MessageSource.SECURITY);

                    remoteMessageService.addSysMsg(smb);
                    logger.debug("增加登录消息");
                }
            });
        } catch (Exception e) {
            logger.error("更新用户登录信息异常",e);
        }
    }


}
